package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.QiniuUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.UUID;

/**
 * @autahor: csl
 * @date: 2019/7/18
 * @description: 套餐控制器
 * @version:1.0
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private SetmealService service;
    @RequestMapping("/findPage")
    public PageResult findAll(@RequestBody QueryPageBean queryPageBean){
         try {
             PageResult page = service.findPage(queryPageBean);
             return new PageResult(page.getTotal(),page.getRows());
         }catch (Exception e){
                     e.printStackTrace();
                     return new PageResult(0L,new ArrayList());
                 }
    }
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[]checkgroupIds){
         try {
             String saveName = setmeal.getImg().replace(QiniuUtils.qiniu_img_url_pre, "");
             setmeal.setImg(saveName);
             service.add(setmeal,checkgroupIds);
             return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS);
         }catch (Exception e){
                     e.printStackTrace();
                     return new Result(false,MessageConst.ADD_SETMEAL_FAIL);
                 }
    }
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
         try {
             String filename = imgFile.getOriginalFilename();
          String saveUploadName=   UUID.randomUUID().toString().replace("-","")+filename;
          QiniuUtils.upload2Qiniu(imgFile.getBytes(),saveUploadName);
             String file_url= QiniuUtils.qiniu_img_url_pre + saveUploadName;
                jedisPool.getResource().sadd(RedisConst.SETMEAL_PIC_RESOURCES,RedisConst.SETMEAL_PIC_DB_RESOURCES);
                return new Result(true,MessageConst.UPLOAD_SUCCESS,file_url);
         }catch (Exception e){
                     e.printStackTrace();
                     return new Result(false,MessageConst.PIC_UPLOAD_FAIL);
                 }
    }
}
